package com.free.mini.common.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.free.mini.common.utils.BizTraceUtil;

import lombok.extern.slf4j.Slf4j;

@WebFilter(filterName = "aBizTraceFilter", urlPatterns = "/*")
@Slf4j
@Component
public class BizTraceFilter implements Filter {

	@Value("${spring.application.name:}")
    private String applicationName;
	
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
		try {
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			String requestURI = request.getRequestURI();
			log.debug("自定义过滤器 NP -> GatewayCore -> BizTraceFilter 触发, 拦截url:{}", requestURI);
			/**
			 * 开启业务链路追踪
			 */
			//获取请求头传过来的日志追踪ID
			String bizTraceId = request.getHeader(BizTraceUtil.BIZ_TRACE_ID);
			//按全部小写获取
			if(StringUtils.isBlank(bizTraceId)) {
				log.debug("get bizTraceId from header by toLowerCase.");
				bizTraceId = request.getHeader(BizTraceUtil.BIZ_TRACE_ID.toLowerCase());
			}
			//按全部大写获取
			if(StringUtils.isBlank(bizTraceId)) {
				log.debug("get bizTraceId from header by toUpperCase.");
				bizTraceId = request.getHeader(BizTraceUtil.BIZ_TRACE_ID.toUpperCase());
			}
			log.debug("start open bizTrace, bizTraceId={}, applicationName={}", bizTraceId, applicationName);
			BizTraceUtil.openTrace(applicationName, bizTraceId);
			log.debug("end open bizTrace, bizTraceId={}", BizTraceUtil.currentTraceId());
			/**
			 * 设置bizTraceId到header
			 */
			if(StringUtils.isBlank(bizTraceId)) {
				log.debug("BizTraceFilter.doFilter -> bizTraceId is null, uri={}.", requestURI);
				MutableHttpServletRequestWrapper mutableHttpServletRequest = new MutableHttpServletRequestWrapper(request);
				mutableHttpServletRequest.putHeader(BizTraceUtil.BIZ_TRACE_ID, BizTraceUtil.currentTraceId());
				filterChain.doFilter(mutableHttpServletRequest, servletResponse);
				return;
			}
			filterChain.doFilter(servletRequest, servletResponse);
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}